package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.InputVerifier;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import model.GroceryListDao;
import model.JTextFieldLimit;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

/**
 * A panel to represent the data that's needed to add an item
 * @author Lawrence Grass
 */
@SuppressWarnings("serial")
public class AddNutritionPanel extends JPanel{
	
	private GroceryListFrame frame;
	
	private JTextField name;
	
	private JTextField calories;
	
	private JTextField cholesterol;
	
	private JTextField sodium;

	private JTextField protein;
	
	private JTextField total_fat;
	
	private JTextField carbohydrates;
	
	private GroceryListDao dao;
	
	public AddNutritionPanel(GroceryListFrame frame, GroceryListDao dao){
		super();
		this.dao = dao;
		this.frame = frame;
		this.setLayout(new BorderLayout());
		JPanel formPanel = new JPanel();
		formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
		
		//name field
		JPanel nameFieldPanel = new JPanel();
		JLabel nameLabel = new JLabel("Item Name: ");
		name = new JTextField(20);
		name.setDocument(new JTextFieldLimit(80));
		nameFieldPanel.add(nameLabel);
		nameFieldPanel.add(name);
		formPanel.add(nameFieldPanel);
		
		//quantity field
		JPanel calorieFieldPanel = new JPanel();
		JLabel calorieLabel = new JLabel("Calories: ");
		calories = new JTextField(20);
		calories.setInputVerifier(new IntVerifier());
		calorieFieldPanel.add(calorieLabel);
		calorieFieldPanel.add(calories);
		formPanel.add(calorieFieldPanel);
		
		JPanel carbFieldPanel = new JPanel();
		JLabel carbLabel = new JLabel("Carbs(grams): ");
		carbohydrates = new JTextField(20);
		carbohydrates.setInputVerifier(new IntVerifier());
		carbFieldPanel.add(carbLabel);
		carbFieldPanel.add(carbohydrates);
		formPanel.add(carbFieldPanel);
		
		JPanel cholesterolFieldPanel = new JPanel();
		JLabel cholesterolLabel = new JLabel("Cholesterol(grams): ");
		cholesterol = new JTextField(20);
		cholesterol.setInputVerifier(new IntVerifier());
		cholesterolFieldPanel.add(cholesterolLabel);
		cholesterolFieldPanel.add(cholesterol);
		formPanel.add(cholesterolFieldPanel);
		
		JPanel sodiumFieldPanel = new JPanel();
		JLabel sodiumLabel = new JLabel("Sodium(grams): ");
		sodium = new JTextField(20);
		sodium.setInputVerifier(new IntVerifier());
		sodiumFieldPanel.add(sodiumLabel);
		sodiumFieldPanel.add(sodium);
		formPanel.add(sodiumFieldPanel);
		
		JPanel proteinFieldPanel = new JPanel();
		JLabel proteinLabel = new JLabel("Protein(grams): ");
		protein = new JTextField(20);
		protein.setInputVerifier(new IntVerifier());
		proteinFieldPanel.add(proteinLabel);
		proteinFieldPanel.add(protein);
		formPanel.add(proteinFieldPanel);
		
		JPanel fatFieldPanel = new JPanel();
		JLabel fatLabel = new JLabel("Fat(grams): ");
		total_fat = new JTextField(20);
		total_fat.setInputVerifier(new IntVerifier());
		fatFieldPanel.add(fatLabel);
		fatFieldPanel.add(total_fat);
		formPanel.add(fatFieldPanel);
		
		this.add(formPanel, BorderLayout.NORTH);
		JPanel buffer = new JPanel();
		buffer.setPreferredSize(new Dimension(400, 340));
		this.add(buffer, BorderLayout.CENTER);
		this.add(controlPanel(), BorderLayout.SOUTH);
	}
	
	/**
	 * A helper method to create the options panel on the bottom of the screen
	 */
	private JPanel controlPanel(){
		JPanel controls = new JPanel();
		controls.setBackground(Color.gray);
		controls.setPreferredSize(new Dimension(400, 50));
		JButton back = new JButton("Back");
		back.setPreferredSize(new Dimension(120, 20));
		back.addActionListener(new ItemFormListener(this));
		controls.add(back);
		JButton done = new JButton("Add Item");
		done.setPreferredSize(new Dimension(120, 20));
		done.addActionListener(new ItemFormListener(this));
		controls.add(done);
		return controls;
	}
	
	/**
	 * A helper mehod to clear the fields
	 */
	private void clearFields(){
		name.setText("");
		carbohydrates.setText("0");
		protein.setText("0");
		cholesterol.setText("0");
		sodium.setText("0");
		total_fat.setText("0");
		calories.setText("0");
	}
	
	/**
	 * An input verifier to make sure the quantity and price are an int and not a string
	 * @author Lawrence Grass
	 */
	private class IntVerifier extends InputVerifier {
		@Override
		public boolean verify(JComponent input) {
			JTextField tf = (JTextField) input;
			try {
				Integer.parseInt(tf.getText());
				return true;
			}
			catch(NumberFormatException exception) {
				return false;
			}
		}	
	}
		
	private class ItemFormListener implements ActionListener {
		private AddNutritionPanel parent;
		private ItemFormListener(AddNutritionPanel AddNutritionPanel){
			this.parent = AddNutritionPanel;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			JButton source = (JButton) e.getSource();
			if(source.getText().equals("Add Item")){
				String item = name.getText();
				try {
					
					//make sure the fields are not empty
					if (item.equals("")) {
						JOptionPane.showMessageDialog(frame,
							    "Items need to have names.");
					} else if (Integer.parseInt(calories.getText()) < 0 || Integer.parseInt(sodium.getText()) < 0
								|| Integer.parseInt(sodium.getText()) < 0 || Integer.parseInt(carbohydrates.getText()) < 0
								|| Integer.parseInt(total_fat.getText()) < 0 || Integer.parseInt(cholesterol.getText()) < 0)
							{
						JOptionPane.showMessageDialog(frame,
							    "There is no such thing as negative matter.");
					} else if (calories.getText().equals("") || carbohydrates.getText().equals("") || protein.getText().equals("")
								|| sodium.getText().equals("") || cholesterol.getText().equals("") || total_fat.getText().equals("")) {
						JOptionPane.showMessageDialog(frame,
							    "Some ingredients are not listed.");
					}else {
						//correct the name to work with MySQL
						if(item.contains("'")){
							item = item.replace("'", "\'");
						}
						//make sure the item isn't already on the list
						if(dao.canAddNutrition(item))
						{
							System.out.println("add the data");
							dao.addToNutritionTable(name.getText(), Integer.parseInt(calories.getText()), Integer.parseInt(total_fat.getText()),
													Integer.parseInt(cholesterol.getText()), Integer.parseInt(sodium.getText()), Integer.parseInt(carbohydrates.getText()), 
													Integer.parseInt(protein.getText()));
							frame.refreshCards();
							frame.goBack();
						}
						else
						{
							int n = JOptionPane.showConfirmDialog(
								    frame,
								    "Item already exists, replace it?",
								    "Existing item encountered",
								    JOptionPane.YES_NO_OPTION);
							if(n == 0)
							{
								dao.deleteNutrition(item);
								dao.addToNutritionTable(name.getText(), Integer.parseInt(calories.getText()), Integer.parseInt(total_fat.getText()),
														Integer.parseInt(cholesterol.getText()), Integer.parseInt(sodium.getText()), Integer.parseInt(carbohydrates.getText()), 
														Integer.parseInt(protein.getText()));
								frame.refreshCards();
								frame.goBack();
							}
						}
					}
				} catch (MySQLIntegrityConstraintViolationException ex){
					JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
				} catch (NumberFormatException e1) {
					//do nothing
				} catch (Exception e1) {
					//keep on trucking
				}
			} else if (source.getText().equals("Back")){
				parent.clearFields();
				frame.refreshCards();
				frame.goBack();
			}
		}
		

		
		
	}
}
